/*
 * Copyright 2012 The LoadTestAnalyzer Project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

$(function() {
	var processQuery = function(query, action, context) {
		var request = {
				url: 'report',
				type: 'POST',
				dataType: 'json',
				data: JSON.stringify(query),
				success: action
			}
		if(context) {
			request.context = context;
		}
		$.ajax(request)
	}
	
	processQuery({
		query: {
			constant_score: {
				filter: {
					prefix: {
						_type: 'data_'
					}
				}
			}
		},
		size: 0
	},
	function(data) {
		$('#record-count').text(data.hits.total);
	})
	
	processQuery({
		query: {
			constant_score: {
				filter: {
					type: {
						value: 'series'
					}
				}
			}
		},
		size: 0
	},
	function(data) {
		$('#series-count').text(data.hits.total);
	})
	
	$('#content-new').button({
		icons: {
			primary: "ui-icon-plusthick"
		}
	})
	.click(function() {
		$('#dlg-new-diagram').dialog('open');
	})
	$('#content-clear').button({
		icons: {
			primary: "ui-icon-closethick"
		}
	})
	.click(function() {
		$('#content-view').empty();
	})
	$('#content-collapse').button({
		icons: {
			primary: "ui-icon-triangle-1-e"
		}
	})
	.click(function() {
		$('#content-view').find('.chartcollapse').addClass('ui-icon-triangle-1-e').removeClass('ui-icon-triangle-1-s');
		$('#content-view').find('div.content').hide();
	})
	$('#content-expand').button({
		icons: {
			primary: "ui-icon-triangle-1-s"
		}
	})
	.click(function() {
		$('#content-view').find('.chartcollapse').addClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e');
		$('#content-view').find('div.content').show();
	})
		
	$('#content-view').delegate('.chartcollapse', 'click', function() {
		$(this).parent().next('div.content').toggle();
		$(this).toggleClass('ui-icon-triangle-1-s').toggleClass('ui-icon-triangle-1-e');
		$(this).parent().find('div').toggle();
	})
	
	var addControls = function(header) {
		header.prepend('<span class="chartcollapse ui-icon ui-icon-triangle-1-s"></span>');
	}
	
	$('#dlg-new-diagram input[name = series], #dlg-delete input[name = series]').autocomplete({
		minLength: 0,
		source: function(request, response) {
			var query = {
					query: {
						constant_score: {
							filter: {
								and: [
								      {type: {value: 'series'}}
								]
							}
						}
					},
					size: 10000,
					fields: ['start'],
					sort: [{
						start: 'asc'
					}]
				};
				
				var seriesname = request.term;
				if(seriesname.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {_id: '*' + seriesname + '*'}}});
				}
			
				processQuery(query,
				function(data) {
					response(data.hits.hits);
				})		
		},
		select: function(event, ui) {
			$('#dlg-new-diagram input[name = series], #dlg-delete input[name = series]').val(ui.item._id);
			return false;
		},
		focus: function(event, ui) {
			$('#dlg-new-diagram input[name = series], #dlg-delete input[name = series]').val(ui.item._id);
			return false;
		}		
	});
	
	
	$('#dlg-new-diagram input[name = series]').data('autocomplete')._renderItem = function( ul, item ) {
		var date = new Date(item.fields.start);
		var dateStr = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
		return $('<li>')
		.data('item.autocomplete', item)
		.append('<a>' + item._id + ' (' + dateStr + ')</a>')
		.appendTo(ul);
	};

	$('#dlg-delete input[name = series]').data('autocomplete')._renderItem = function( ul, item ) {
		var date = new Date(item.fields.start);
		var dateStr = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
		return $('<li>')
		.data('item.autocomplete', item)
		.append('<a>' + item._id + ' (' + dateStr + ')</a>')
		.appendTo(ul);
	};

	$('#dlg-new-diagram input[name = host]').autocomplete({
		minLength: 0,
		source: function(request, response) {
			var hostname = request.term;
			var type = $('#dlg-new-diagram input[name = type]').val();
			var category = $('#dlg-new-diagram input[name = category]').val();
			
			var query = {
					query: {
						constant_score: {
							filter: {
								and: [
							     	{prefix: {_type: 'data_'}},
									{term: {_parent: $('#dlg-new-diagram input[name = series]').val()}}
								]
							}
						}
					},
					facets: {
						hosts: {
							terms: {
								field: 'hostname',
								size: 100
							}
						}
					},
					size: 0
				}
				
				if(hostname.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {hostname: '*' + hostname + '*'}}});
				}
				if(type.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {_type: 'data_*' + type + '*'}}});
					
				}
				if(category.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {category: '*' + category + '*'}}});
				}
				
				processQuery(query,
					function(data) {
						response(data.facets.hosts.terms);
					})
		},
		select: function(event, ui) {
			$('#dlg-new-diagram input[name = host]').val(ui.item.term);
			return false;
		},
		focus: function(event, ui) {
			$('#dlg-new-diagram input[name = host]').val(ui.item.term);
			return false;
		}
	})
	.data('autocomplete')._renderItem = function( ul, item ) {
		return $('<li>')
		.data('item.autocomplete', item)
		.append('<a>' + item.term + ' (' + item.count + ' records)</a>')
		.appendTo(ul);
	};
	
	$('#dlg-new-diagram input[name = type]').autocomplete({
		minLength: 0,
		source: function(request, response) {
			var hostname = $('#dlg-new-diagram input[name = host]').val();
			var type = request.term;
			var category = $('#dlg-new-diagram input[name = category]').val();
			
			var query = {
					query: {
						constant_score: {
							filter: {
								and: [
							     	{prefix: {_type: 'data_'}},
									{term: {_parent: $('#dlg-new-diagram input[name = series]').val()}}
								]
							}
						}
					},
					facets: {
						types: {
							terms: {
								field: '_type',
								size: 100
							}
						}
					},
					size: 0
				}
				
				if(hostname.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {hostname: '*' + hostname + '*'}}});
				}
				if(type.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {_type: 'data_*' + type + '*'}}});
					
				}
				if(category.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {category: '*' + category + '*'}}});
				}
				
				processQuery(query,
					function(data) {
						var types = data.facets.types.terms;
						for(var t = 0; t < types.length; t++) {
							types[t].term = types[t].term.substr(5);
						}
						response(data.facets.types.terms);
					})
		},
		select: function(event, ui) {
			$('#dlg-new-diagram input[name = type]').val(ui.item.term);
			return false;
		},
		focus: function(event, ui) {
			$('#dlg-new-diagram input[name = type]').val(ui.item.term);
			return false;
		}
	})
	.data('autocomplete')._renderItem = function( ul, item ) {
		return $('<li>')
		.data('item.autocomplete', item)
		.append('<a>' + item.term + ' (' + item.count + ' records)</a>')
		.appendTo(ul);
	};
	
	$('#dlg-new-diagram input[name = category]').autocomplete({
		minLength: 0,
		source: function(request, response) {
			var hostname = $('#dlg-new-diagram input[name = host]').val();
			var type = $('#dlg-new-diagram input[name = type]').val();
			var category = request.term;
			
			var query = {
					query: {
						constant_score: {
							filter: {
								and: [
							     	{prefix: {_type: 'data_'}},
									{term: {_parent: $('#dlg-new-diagram input[name = series]').val()}}
								]
							}
						}
					},
					facets: {
						categories: {
							terms: {
								field: 'category',
								size: 100
							}
						}
					},
					size: 0
				}
			
				if(hostname.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {hostname: '*' + hostname + '*'}}});
				}
				if(type.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {_type: 'data_*' + type + '*'}}});
					
				}
				if(category.length > 0) {
					query.query.constant_score.filter.and.push({query: {wildcard: {category: '*' + category + '*'}}});
				}
				
				processQuery(query,
					function(data) {
						response(data.facets.categories.terms);
					})
		},
		select: function(event, ui) {
			$('#dlg-new-diagram input[name = category]').val(ui.item.term);
			return false;
		},
		focus: function(event, ui) {
			$('#dlg-new-diagram input[name = category]').val(ui.item.term);
			return false;
		}
	})
	.data('autocomplete')._renderItem = function( ul, item ) {
		return $('<li>')
		.data('item.autocomplete', item)
		.append('<a>' + item.term + ' (' + item.count + ' records)</a>')
		.appendTo(ul);
	};

	
//-------------------------------------------------------------------------------------------------------
// Chart renderers
//-------------------------------------------------------------------------------------------------------
	var renderTimepointCharts = function(seriesname, categories, typeContainer, hostname, typename) {
		for(var c = 0; c < categories.length; c++) {
			var category = categories[c].term;
			var chartName = seriesname + '-' + 
			hostname + '-' + 
			typename.substr(5) + '-' + 
			category;			
			var chartContainer = typeContainer.find('div[name = "' + chartName + '"]');
			if(chartContainer.size() == 0) {
				chartContainer = $('<div class="plot-container" name="' + 
						chartName + '"><h5 class="chartheader ui-widget-header">' + 
						seriesname + ' | ' +
						hostname + ' | ' + 
						typename.substr(5) + ' | ' +
						category + '</h5><div class="content"><div class="plot"></div><div class="<div class="stats"></div></div></div>').appendTo(typeContainer);
				addControls(chartContainer.find('h5'));
      		  	var query = {
  					query: {
  						constant_score: {
  							filter: {
  								and: [
  									{term: {_parent: seriesname}},
  							     	{term: {'hostname': hostname}},
  							     	{term: {_type: typename}},
  							     	{term: {category: category}}
  								]
  							}
  						}
  					},
  					sort: [{timestamp: {order: 'asc'}}],
  					size: 100000
  				}
      		  	processQuery(query, function(data) {
      		  		if(data.hits.total == 0) {
      		  			$(this).remove();
      		  			return;
      		  		}
      		  		
					datasets = {};
					var hit = data.hits.hits[0]._source;
					for(var v in hit.values) {
						datasets[v] = {label: v, data: [[hit.timestamp, hit.values[v]]]};
					}
  		  			for(var d = 1; d < data.hits.hits.length; d++) {
  		  				hit = data.hits.hits[d]._source;
  		  				for(var v in hit.values) {
							datasets[v].data.push([hit.timestamp, hit.values[v]]);
						}
  		  			}
					var data = [];
					for(var d in datasets) {
						data.push(datasets[d]);
					}
					var placeholder = $(this).find('div.plot');
					$.plot(placeholder, data, { xaxis: { mode: 'time', timezone: 'browser'}, yaxis: {labelWidth: 50}, selection: { mode: "x" }});
      			}, chartContainer);	
			}
		}
	}
	
	var renderGrinderCharts = function(seriesname, categories, typeContainer, hostname, typename) {
		for(var c = 0; c < categories.length; c++) {
			var category = categories[c].term;
			var chartName = seriesname + '-' + 
			hostname + '-' + 
			typename.substr(5) + '-' + 
			category + '-';
			var chartContainer = typeContainer.find('div[name = "' + chartName + '"]');
			if(chartContainer.size() == 0) {
				chartContainer = $('<div class="plot-container" name="' + 
						chartName + '"><h5 class="chartheader ui-widget-header">' + 
						seriesname + ' | ' + 
						typename.substr(5) + 
						' | Test ' + category + 
						' | TPS</h5><div class="content"><div class="plot"></div><div class="stats"></div></div></div>').appendTo(typeContainer);
				addControls(chartContainer.find('h5'));

				//store query parameter for later use
				chartContainer.find('div.stats').data('queryparams', {
					'seriesname': seriesname,
					'hostname': hostname,
					'_type': typename,
					'category': category,
					'fieldnames': []
				});
				
				var BUCKET_SIZE = '10s';
      		  	var query = {
      					query: {
      						constant_score: {
      							filter: {
      								and: [
      									{term: {_parent: seriesname}},
      							     	{term: {'hostname': hostname}},
      							     	{term: {_type: typename}},
      							     	{term: {category: category}}
      								]
      							}
      						}
      					},
      					facets: {
      						testtime: {
      							date_histogram: {
      								key_field: 'timestamp',
      								value_field: 'testtime',
      								interval: BUCKET_SIZE
      							}
      						},
	  						ttrh: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'ttrh',
	  								interval: BUCKET_SIZE
	  							}
	  						},
	  						ttec: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'ttec',
	  								interval: BUCKET_SIZE
	  							}
	  						},
	  						ttfb: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'ttfb',
	  								interval: BUCKET_SIZE
	  							}
	  						},
	  						errors: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'errors',
	  								interval: BUCKET_SIZE
	  							}
	  						},
	  						responseerrors: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'responseerrors',
	  								interval: BUCKET_SIZE
	  							}
	  						},
	  						responselength: {
	  							date_histogram: {
	  								key_field: 'timestamp',
	  								value_field: 'responselength',
	  								interval: BUCKET_SIZE
	  							}
	  						}
      					},
      					size: 0
      				}
          		  	processQuery(query, function(data) {
          		  		if(data.hits.total == 0) {
          		  			$(this).remove();
          		  			return;
          		  		}
          		  		
          		  		var chartDataTPS = [];
          		  		var chartDataTime = [];
          		  		var chartErrors = [];
          		  		var chartBytes = [];
          		  		
          		  		var tps = {label: 'tps/s', data: []};
          		  		
          		  		var rtime = {label: 'response time (ms)', data: []};
          		  		var ttrh = {label: 'time to resolve host (ms)', data: []};
          		  		var ttec = {label: 'time to establish connection (ms)', data: []};
          		  		var ttfb = {label: 'time to first byte (ms)', data: []};
          		  		var errors = {label: 'errors', data: []};
          		  		var rerrors = {label: 'response errors', data: []};
          		  		var bytes = {label: 'response bytes/s', data: []};
          		  		
          		  		var rt_entries = data.facets.testtime.entries;
          		  		var ttrh_entries = data.facets.ttrh.entries;
          		  		var ttec_entries = data.facets.ttec.entries;
          		  		var ttfb_entries = data.facets.ttfb.entries;
          		  		var error_entries = data.facets.errors.entries;
          		  		var rerror_entries = data.facets.responseerrors.entries;
          		  		var bytes_entries = data.facets.responselength.entries;
          		  		
          		  		for(var e = 0; e < rt_entries.length; e++) {
          		  			tps.data.push([rt_entries[e].time, rt_entries[e].count / 10]); //bucketsize = 10s

          		  			ttrh.data.push([ttrh_entries[e].time, ttrh_entries[e].mean]);
          		  			ttec.data.push([ttec_entries[e].time, ttec_entries[e].mean - ttrh_entries[e].mean]);
          		  			ttfb.data.push([ttfb_entries[e].time, ttfb_entries[e].mean - ttec_entries[e].mean]);
          		  			rtime.data.push([rt_entries[e].time, rt_entries[e].mean - ttfb_entries[e].mean]);
          		  			errors.data.push([error_entries[e].time, error_entries[e].total]);
          		  			rerrors.data.push([rerror_entries[e].time, rerror_entries[e].total]);
          		  			
          		  			bytes.data.push([bytes_entries[e].time, bytes_entries[e].total / 10]); //bucketsize = 10s          		  			
          		  		}
          		  		chartDataTPS.push(tps);
          		  		chartDataTime.push(ttrh);
          		  		chartDataTime.push(ttec);
          		  		chartDataTime.push(ttfb);
          		  		chartDataTime.push(rtime);
          		  		chartErrors.push(errors);
          		  		chartErrors.push(rerrors);
          		  		chartBytes.push(bytes)
          		  		
          		  		var chartBaseName = $(this).attr('name');
          		  		var chartBaseTitle = $(this).find('h5').text();
          		  		chartBaseTitle = chartBaseTitle.substring(0, chartBaseTitle.length - 3);
          		  		$(this).attr('name', chartBaseName + 'tps');
          		  	
						var placeholder = $(this).find('div.plot');
						$.plot(placeholder, chartDataTPS, {points: {show: true}, lines: {show: true}, xaxis: { mode: 'time', timezone: 'browser'}, yaxis: {labelWidth: 50}, selection: { mode: "x" }});

						var chartContainer = $('<div class="plot-container" name="' + 
								chartBaseName + 'timing"><h5 class="chartheader ui-widget-header">' + 
								chartBaseTitle + 
								'Timing</h5><div class="content"><div class="plot"></div><div class="stats"></div></div></div>').appendTo($(this).parent());						
						addControls(chartContainer.find('h5'));

						//store query parameter for later use
						chartContainer.find('div.stats').data('queryparams', {
							'seriesname': seriesname,
							'hostname': hostname,
							'_type': typename,
							'category': category,
							'fieldnames': ['ttrh', 'ttec', 'ttfb', 'testtime']
						});
						
						placeholder = chartContainer.find('div.plot');
						$.plot(placeholder, chartDataTime, {series: {stack: true}, lines: {show: true, fill: true}, xaxis: { mode: 'time', timezone: 'browser'}, yaxis: {labelWidth: 50}, selection: { mode: "x" }});
						
						chartContainer = $('<div class="plot-container" name="' + 
								chartBaseName + 'errors"><h5 class="chartheader ui-widget-header">' + 
								chartBaseTitle + 
								'Errors</h5><div class="plot"></div></div>').appendTo($(this).parent());
						addControls(chartContainer.find('h5'));

						//store query parameter for later use
						chartContainer.find('div.stats').data('queryparams', {
							'seriesname': seriesname,
							'hostname': hostname,
							'_type': typename,
							'category': category,
							'fieldnames': ['errors', 'responseerrors']
						});
						
						placeholder = chartContainer.find('div.plot');
						$.plot(placeholder, chartErrors, {
							series: {stack: true}, 
							bars: {show: true, fill: true, barWidth: 9000}, //a bit less than 10s (bucketsize) 
							xaxis: { mode: 'time', timezone: 'browser'}, 
							yaxis: {min: 0, labelWidth: 50},
							selection: { mode: "x" }});
						
						chartContainer = $('<div class="plot-container" name="' + 
								chartBaseName + 'bytes"><h5 class="chartheader ui-widget-header">' + 
								chartBaseTitle + 
								'Response bytes/s</h5><div class="content"><div class="plot"></div><div class="stats"></div></div></div>').appendTo($(this).parent());
						addControls(chartContainer.find('h5'));
						
						//store query parameter for later use
						chartContainer.find('div.stats').data('queryparams', {
							'seriesname': seriesname,
							'hostname': hostname,
							'_type': typename,
							'category': category,
							'fieldnames': ['responsebytes']
						});
						
						placeholder = chartContainer.find('div.plot');
						$.plot(placeholder, chartBytes, {points: {show: true}, lines: {show: true}, xaxis: { mode: 'time', timezone: 'browser'}, yaxis: {labelWidth: 50}, selection: { mode: "x" }});
          		  	}, chartContainer);					
			}
		}
	}
	
//-------------------------------------------------------------------------------------------------------
// Chart renderers END
//-------------------------------------------------------------------------------------------------------

	var renderCharts = function(seriesname, hostname, type, category) {
	  //get all possible graphs; maybe a combination does not contain data
		var query = {
			query: {
				constant_score: {
					filter: {
						and: [
					     	{prefix: {_type: 'data_'}},
							{term: {_parent: seriesname}}
						]
					}
				}
			},
			facets: {
				categories: {
					terms: {
						field: 'category',
						size: 1000,
						order: 'term'
					}
				},
				types: {
					terms: {
						field: '_type',
						size: 1000,
						order: 'term'
					}
				},
				hosts: {
					terms: {
						field: 'hostname',
						size: 1000,
						order: 'term'
					}
				}
			},
			size: 0
		}
	
		if(hostname.length > 0) {
			query.query.constant_score.filter.and.push({query: {wildcard: {hostname: '*' + hostname + '*'}}});
		}
		if(type.length > 0) {
			query.query.constant_score.filter.and.push({query: {wildcard: {_type: 'data_*' + type + '*'}}});
			
		}
		if(category.length > 0) {
			query.query.constant_score.filter.and.push({query: {wildcard: {category: '*' + category + '*'}}});
		}
		
		processQuery(query,
			function(data) {
				var hosts = data.facets.hosts.terms;
				var types = data.facets.types.terms;
				var categories = data.facets.categories.terms;
				var container = $('#content-view');
				for(var h = 0; h < hosts.length; h++) {
					var hostname = hosts[h].term;
					for(var t = 0; t < types.length; t++) {
						var typename = types[t].term;
						if(typename == 'data_Grinder') {
							renderGrinderCharts(seriesname, categories, container, hostname, typename);
						} else {
							renderTimepointCharts(seriesname, categories, container, hostname, typename);
						}
					}
				}
				
			})			                    					
	}
	
	$('#dlg-new-diagram').dialog({autoOpen: false,
		                          modal: true,
		                          width: 'auto',
		                          resizable: false,
		                          buttons: {
		                        	  Cancel: function() {
		                        		  $(this).dialog('close');
		                        	  },
		                        	  Add: function() {
		                        		  $(this).dialog('close');
		                       
		                        		  var hostname = $('#dlg-new-diagram input[name = host]').val();
		                        		  var type = $('#dlg-new-diagram input[name = type]').val();
		                        		  var category = $('#dlg-new-diagram input[name = category]').val();
		                        		  var seriesname = $('#dlg-new-diagram input[name = series]').val();
	
		                        		  renderCharts(seriesname, hostname, type, category);
		                       	  	}
		                       }});

	$('#content-view').sortable({handle: 'h5'});
	
	$('#content-delete').button({
		icons: {
			primary: "ui-icon-minusthick"
		}
	}).click(function() {
		$('#dlg-delete').dialog('open');		
	})
	
	$('#dlg-delete').dialog({autoOpen: false,
		                          modal: true,
		                          width: 'auto',
		                          resizable: false,
		                          buttons: {
		                        	  Cancel: function() {
		                        		  $(this).dialog('close');
		                        	  },
		                        	  Delete: function() {
		                        		  $(this).dialog('close');
		                       
		                        		  var seriesname = $('#dlg-delete input[name = series]').val();
		                        		  
		                        		  deleteSeries(seriesname);
		                        	  }
		                       }});
	
	var deleteSeries = function(seriesname) {
		var query = {
				query: {
					constant_score: {
						filter: {
							and: [
							      {type: {value: 'series'}}
							]
						}
					}
				},
				size: 0
			};
			
			if(seriesname.length > 0) {
				query.query.constant_score.filter.and.push({query: {wildcard: {_id: '*' + seriesname + '*'}}});
			}
		
			processQuery(query,
			function(data) {
				if(confirm("Delete " + data.hits.total + " series?")) {
					$.ajax({url: '../admin/delete',
							type: 'POST',
							dataType: 'json',
							data: {series: seriesname},
							success: function() {
								alert("Series deleted and datastore optimized.");
							}
					})	
				}
			})		
		
	}

	//Selection handling
	$(document).delegate('div.plot', 'plotselected', function (event, ranges) {
		//TODO limit action to current series: Should we do so? 
		//If not, we can show statistics for the same timerange,even for different series
		$(document).find('div.plot').each(function() {
			var plot = $(this).data('plot');
			var data = plot.getData();
			var options = plot.getOptions();
			options.grid = {markings: [{color: '#f0f0f0', xaxis: { from: ranges.xaxis.from, to: ranges.xaxis.to }}]};
			$.plot($(this), data, options);
			
			//TODO calculation of statistics
			
		});		
	})
	
	$(document).delegate('div.plot', 'plotunselected', function (event, ranges) {
		//TODO limit action to current series
		$(document).find('div.plot').each(function() {
			var plot = $(this).data('plot');
			var data = plot.getData();
			var options = plot.getOptions();
			options.grid = {markings: []};
			$.plot($(this), data, options);
		});		
	})
	
	
	//if the url has a querystring, use it to configure the chart display
	if(location.search.length > 1) {
		var parts = location.search.substring(1).split('&');

	    for (var i = 0; i < parts.length; i++) {
	        var nv = parts[i].split('=');
	        if (!nv[0]) continue;
	        var name = decodeURIComponent(nv[0]);
	        if(name[0] == 'q') {
	        	var value = decodeURIComponent(nv[1]);
	        	params = value.split('|');
	        	if(params.length == 4) {
	        		renderCharts(params[0], params[1], params[2], params[3]);
	        	}
	        }
	    }
	}
});
